package net.zjitc.servlet.log;

import net.zjitc.daomain.User;
import net.zjitc.service.UserService;
import net.zjitc.service.UserServiceImpl.UserServiceImpl;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.sql.SQLException;

/**
 * Created by hasee on 2017/9/27.
 */
@WebServlet(name = "LogonServlet",urlPatterns = "/logonServlet")
public class LogonServlet extends HttpServlet {
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        request.setCharacterEncoding("utf-8");
        response.setContentType("text/html;charset=utf-8");
        PrintWriter out = response.getWriter();

        String username = request.getParameter("username");
        String password = request.getParameter("password");
        String checkpassword = request.getParameter("check_password");
        String error = "";

        UserService userService = new UserServiceImpl();
        User user = null;
        try {
            if(username==""){//判定输入格式
                error ="用户名不能为空";
            }else if(password==""){
                error = "密码不能为空";
            }else if(!password.equals(checkpassword)){
                error = "两次输入密码不一致";
            }else {
                user = userService.logon(username,password);//输入格式没错，连数据库插数据
                if(user==null){//插不进去，用户名已存在
                    error = "用户名已存在";
                }
            }
        } catch (SQLException e) {
            e.getStackTrace();
        }
        if(user==null){
            request.setAttribute("error",error);
            request.getRequestDispatcher("/log/logon.jsp").forward(request,response);
        }
        if(user!=null){
                response.sendRedirect("/web/log/login.jsp");
        }
    }

    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

    }
}
